<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Chat Room</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }
    #messages {
      height: 300px;
      overflow-y: scroll;
      border: 1px solid #ccc;
      padding: 10px;
      margin-bottom: 10px;
    }
    input {
      width: calc(100% - 60px);
      padding: 5px;
    }
    button {
      width: 50px;
      padding: 5px;
    }
  </style>
</head>
<body>
  <h1>WebSocket Chat Room</h1>
  <div id="messages"></div>
  <input type="text" id="messageInput" placeholder="Type a message..." />
  <button id="sendButton">Send</button>

  <script>
    const ws = new WebSocket("ws://localhost:8080");

    const messagesDiv = document.getElementById("messages");

    function showMessage(message) {
      const messageElement = document.createElement("p");
      messageElement.textContent = message;
      messagesDiv.appendChild(messageElement);
      messagesDiv.scrollTop = messagesDiv.scrollHeight; // 自动滚动到底部
    }

    // 显示接收到的消息
    ws.onmessage = (event) => {
      showMessage(event.data);
    };

    // 发送消息到服务器
    document.getElementById("sendButton").addEventListener("click", () => {
      const input = document.getElementById("messageInput");
      let message = input.value + "";
      if (message) {
        console.log(message instanceof String)
        ws.send(message); // 发送消息
        input.value = ""; // 清空输入框
        showMessage(message);
      }
    });

    // 监听回车键发送消息
    document.getElementById("messageInput").addEventListener("keypress", (e) => {
      if (e.key === "Enter") {
        document.getElementById("sendButton").click();
      }
    });
  </script>
</body>
</html>